package io.afu.validator.Implement;

import io.afu.validator.Annimation.ChineseIdCard;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ChineseIdCardValidatorImpl implements ConstraintValidator<ChineseIdCard,String> {

    private boolean allowEmpty;

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        if (null == s || s.equals("")){
            return allowEmpty;
        }else {
            String str = s.trim();
            int length = str.length();
            if (length != 15 && length != 18){
                // System.out.println("非法身份证："+idcard);
                return false;
            }
            if (length == 15){
                // 15位的身份证验证器并没有写好，请各位自行补充
                return true;
            }
            String patten = "^(11|12|13|14|15|21|22|23|31|32|33|34|35|36|37|41|42|43|44|45|46|51|52|53|54|50|61|62|63|64|65|71|81|82)\\d{4}([1-3][0-9])\\d{9}(\\d|X|x)$";
            Pattern p = Pattern.compile(patten);
            Matcher m = p.matcher(str);
            return m.find();
        }
    }

    @Override
    public void initialize(ChineseIdCard constraintAnnotation) {
        this.allowEmpty = constraintAnnotation.allowEmpty();
    }
}
